from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone

class UserManager(BaseUserManager):
    """
    自定义用户管理器
    用于创建普通用户和超级用户
    """
    def create_user(self, email, password=None, **extra_fields):
        """
        创建普通用户
        :param email: 用户邮箱
        :param password: 用户密码
        :param extra_fields: 其他字段
        :return: 用户对象
        """
        if not email:
            raise ValueError('用户必须提供邮箱地址')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        """
        创建超级用户
        :param email: 用户邮箱
        :param password: 用户密码
        :param extra_fields: 其他字段
        :return: 用户对象
        """
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self.create_user(email, password, **extra_fields)

class User(AbstractBaseUser, PermissionsMixin):
    """
    自定义用户模型
    继承自AbstractBaseUser和PermissionsMixin
    """
    email = models.EmailField(unique=True, verbose_name='邮箱')
    username = models.CharField(max_length=150, unique=True, verbose_name='用户名')
    phone = models.CharField(max_length=11, unique=True, null=True, blank=True, verbose_name='手机号')
    avatar = models.CharField(max_length=255, null=True, blank=True, verbose_name='头像地址')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    is_staff = models.BooleanField(default=False, verbose_name='是否管理员')
    date_joined = models.DateTimeField(default=timezone.now, verbose_name='注册时间')
    last_login = models.DateTimeField(null=True, blank=True, verbose_name='最后登录时间')

    objects = UserManager()

    USERNAME_FIELD = 'email'  # 使用邮箱作为登录字段
    REQUIRED_FIELDS = ['username']  # 创建超级用户时需要的字段

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = '用户'

    def __str__(self):
        return self.username

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username
